package com.coalmine.api.plugin;

import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class PluginManager {

    private static Map<String, CachePlugin> cachePluginMap = new ConcurrentHashMap<>();
    private static Map<String, TransResultFieldPlugin> transResultFieldPluginMap = new ConcurrentHashMap<>();
    private static Map<String, TransResultSetPlugin> transResultSetPluginMap = new ConcurrentHashMap<>();

    public static void loadPlugins() {
        ServiceLoader<CachePlugin> serviceLoader = ServiceLoader.load(CachePlugin.class);
        Iterator<CachePlugin> CachePlugins = serviceLoader.iterator();
        while (CachePlugins.hasNext()) {
            CachePlugin plugin = CachePlugins.next();
            plugin.init();
            log.info(plugin.getClass().getName());
            cachePluginMap.put(plugin.getClass().getName(), plugin);
        }
        log.info("scan cache plugin finish");

        ServiceLoader<TransResultFieldPlugin> serviceLoader2 = ServiceLoader.load(TransResultFieldPlugin.class);
        Iterator<TransResultFieldPlugin> transResultFieldPluginIterator = serviceLoader2.iterator();
        while (transResultFieldPluginIterator.hasNext()) {
            TransResultFieldPlugin plugin = transResultFieldPluginIterator.next();
            plugin.init();
            log.info(plugin.getClass().getName());
            transResultFieldPluginMap.put(plugin.getClass().getName(), plugin);
        }
        log.info("scan transResultField plugin finish");

        ServiceLoader<TransResultSetPlugin> serviceLoader3 = ServiceLoader.load(TransResultSetPlugin.class);
        Iterator<TransResultSetPlugin> transResultSetPlugin = serviceLoader3.iterator();
        while (transResultSetPlugin.hasNext()) {
            TransResultSetPlugin plugin = transResultSetPlugin.next();
            plugin.init();
            log.info(plugin.getClass().getName());
            transResultSetPluginMap.put(plugin.getClass().getName(), plugin);
        }
        log.info("scan transResultSet plugin finish");
    }

    public static CachePlugin getCachePlugin(String className) {
        return cachePluginMap.get(className);
    }
    public static TransResultFieldPlugin getTransResultFieldPlugin(String className) {
        return transResultFieldPluginMap.get(className);
    }

    public static TransResultSetPlugin getTransResultSetPlugin(String className) {
        return transResultSetPluginMap.get(className);
    }

    public static Set<String> getAllCachePlugin(){
        return cachePluginMap.keySet();
    }
    public static Set<String> getAllTransResultField(){
        return transResultFieldPluginMap.keySet();
    }

    public static Set<String> getAllTransResultSetPlugin(){
        return transResultSetPluginMap.keySet();
    }
}
